<template>
  <div class="dynamicSend">
    <el-input class="inputA" clearable v-model="input1">
      <template slot="prepend">动态内容</template>
    </el-input>
    <el-button @click="search">搜索</el-button>
    <br />
    <br />
    <el-radio-group v-model="index" fill="#39383d" @change="search">
      <el-radio-button label="1">未发送</el-radio-button>
      <el-radio-button label="2">已发送</el-radio-button>
    </el-radio-group>
    <br /><br />
    <el-card>
      <div>
        <el-button
          class="btnA"
          size="small"
          @click="addBtn"
          icon="el-icon-edit"
          v-show="index == 1"
          >新增</el-button
        >
        <el-button
          class="btnA"
          size="small"
          @click="importBtn"
          icon="el-icon-upload"
          v-if="false"
          >导入</el-button
        >
      </div>
      <el-table
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="date" label="图片">
          <template slot-scope="scope">
            <el-badge
              v-if="
                scope.row.img.length != 0 && scope.row.img[0].media_type == 1
              "
              :value="scope.row.img.length"
              class="item"
              type="info"
            >
              <el-image
                v-if="scope.row.img.length != 0"
                style="width: 80px; height: 100px"
                :src="scope.row.img[0].path"
                :preview-src-list="srcList(scope.row.img)"
              >
              </el-image>
            </el-badge>
            <video
              v-else
              :src="scope.row.img[0].path"
              class="video"
              controls="controls"
            >
              您的浏览器不支持视频播放
            </video>
          </template>
        </el-table-column>
        <el-table-column prop="content" label="内容"> </el-table-column>
        <el-table-column prop="address" label="操作">
          <template slot-scope="scoped">
            <el-button
              size="small"
              type="info"
              plain
              @click="del(scoped.row.id)"
              v-if="scoped.row.status == 0 || scoped.row.status == 1"
              >删除</el-button
            >
            <!-- <el-button size="small" type="primary" plain>编辑</el-button> -->
            <el-button
              size="small"
              type="success"
              plain
              @click="send(scoped.row.id)"
              v-if="scoped.row.status == 0"
              >发布</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="page"
        :limit.sync="pageSize"
        @pagination="getList"
      >
        <template #left>
          <el-button size="small" v-show="index == 1" @click="delAll"
            >批量删除</el-button
          >
          <el-button size="small" v-show="index == 1" @click="sendAll"
            >批量发布</el-button
          >
        </template>
      </pagination>
    </el-card>
    <el-dialog
      :title="title"
      :visible.sync="dialogTableVisible"
      width="600px"
      @closed="close"
    >
      <el-form
        ref="form"
        :rules="rules"
        :model="form"
        label-width="100px"
        label-position="left"
      >
        <el-form-item label="内容" prop="content">
          <el-input
            v-model="form.content"
            size="small"
            type="textarea"
          ></el-input>
        </el-form-item>
        <el-form-item label="附件类型" prop="content">
          <el-radio v-model="imgType" label="1">图片</el-radio>
          <el-radio v-model="imgType" label="2">视频</el-radio>
        </el-form-item>
        <el-form-item label="图片上传" v-if="imgType == 1">
          <el-upload
            class="avatar-uploader"
            :http-request="upLoad"
            :before-upload="beforeUpload"
            :on-preview="handlePictureCardPreview"
            :on-success="handleAvatarSuccess"
            :show-file-list="false"
            accept=".gif,.jpg,.jpeg,.png,.GIF,.JPG,.PNG"
            action
          >
            <span v-if="form.dialogImageUrl.length != 0">
              <span v-for="(item, index) in form.dialogImageUrl" :key="index">
                <img
                  :src="item"
                  class="avatar"
                  style="width: 80px; height: 80px"
                />
                <i class="el-icon-delete" @click.stop="clear(index)"></i>
              </span>
            </span>
            <i class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="视屏上传" v-if="imgType == 2">
          <el-upload
            class="avatar-uploader el-upload--text"
            action
            :http-request="upLoadA"
            :show-file-list="false"
            :on-success="handleVideoSuccess"
            :before-upload="beforeUploadVideo"
          >
            <!-- v-if="form.dialogImageUrl.length != 0" -->
            <video
              v-if="form.video"
              :src="form.video"
              class="video"
              controls="controls"
            >
              您的浏览器不支持视频播放
            </video>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="发布类型" prop="type">
          <el-radio v-model="form.type" label="1">稍后发布</el-radio>
          <el-radio v-model="form.type" label="2">立即发布</el-radio>
        </el-form-item>
      </el-form>
      <div class="submit">
        <el-button size="small" @click="dialogTableVisible = false"
          >取消</el-button
        >
        <el-button
          size="small"
          type="primary"
          @click="submit"
          :loading="loading"
          >提交</el-button
        >
      </div>
    </el-dialog>
    <el-dialog
      title="导入动态"
      :visible.sync="dialogTableVisibleB"
      width="600px"
      @closed="closeB"
    >
      <el-steps :active="active" align-center>
        <el-step
          title="上传excel文件"
          description="仅支持xlsx格式文件"
        ></el-step>
        <el-step
          title="上传图片压缩包"
          description="仅支持zip格式的压缩包"
        ></el-step>
        <el-step title="提交"></el-step>
      </el-steps>
      <div class="up">
        <input
          v-show="active === 0"
          id="upload"
          type="file"
          @change="importfxx(this)"
          accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
        />
      </div>
      <div v-show="active === 1" class="up">
        <el-upload
          class="upload-demo"
          drag
          :http-request="upLoadA"
          :before-upload="beforeUploadA"
          action
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
        <el-progress :percentage="progress"></el-progress>
      </div>
      <div class="up" v-if="active === 2">
        <el-button type="primary" @click="submitA">提交</el-button>
      </div>
      <div style="color: red">{{ txt }}</div>
    </el-dialog>

    <!-- <input
      id="upload"
      type="file"
      @change="importfxx(this)"
      accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
    /> -->
  </div>
</template>

<script>
import Pagination from "@/components/Pagination"; // 分页
import { ossToken } from "@/api/NotificationManagement";
import { client } from "@/utils/oss.js";
import {
  dynamicAdd,
  dynamicList,
  dynamicDel,
  dynamicSend,
} from "@/api/operationManagement";
import JsZip from "jszip";
export default {
  components: { Pagination },
  data() {
    return {
      active: 0,
      index: "1",
      input1: "",
      tableData: [],
      total: 0,
      page: 1,
      pageSize: 10,
      title: "新增动态",
      dialogTableVisible: false,
      dialogTableVisibleB: false,
      imgType: "1",
      form: {
        content: "",
        dialogImageUrl: [],
        video: "",
        type: "",
        id: "",
        img: [],
      },
      disabled: false,
      rules: {
        content: [{ required: true, message: "请输入内容", trigger: "blur" }],
        dialogImageUrl: [
          { required: true, message: "请上传图片", trigger: "blur" },
        ],
        type: [{ required: true, message: "请选择发布类型", trigger: "blur" }],
      },
      ckeck: [],
      loading: false,
      width: "",
      height: "",
      txt: "",
      plArr: [],
      uped: 0,
      progress: 0,
    };
  },
  methods: {
    clear(index) {
      this.form.dialogImageUrl.splice(index, 1);
      this.form.img.splice(index, 1);
    },
    addBtn() {
      this.title = "新增动态";
      this.dialogTableVisible = true;
    },
    handleRemove(file) {
      console.log(file);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleDownload(file) {
      console.log(file);
    },
    //覆盖默认的上传行为，自定义上传的实现
    async upLoad(file) {
      await ossToken({
        type: 0,
      }).then((res) => {
        if (res.code == 0) {
          this.dataObj = {
            accessKeyId: res.data.accessKey,
            accessKeySecret: res.data.accessSecret,
            securityToken: res.data.token,
            region: "oss-cn-hangzhou",
            bucket: res.data.bucket,
          };
        }
      });
      const self = this;
      let files = file.file,
        point = files.name.lastIndexOf("."),
        suffix = files.name.substr(point),
        fileName = files.name.substr(0, point),
        date = Date.parse(new Date()),
        // fileNames = "/img/" + file.file.name;
        fileNames =
          "/img/" +
          Math.round(new Date() / 1000) +
          "." +
          file.file.name.substring(file.file.name.lastIndexOf(".") + 1);
      console.log(fileNames);
      // console.log(file.file.name.substring(file.file.name.lastIndexOf(".")+1));
      //fileNames上传文件的名称
      //file.file上传文件的内容
      client(this.dataObj)
        .multipartUpload(fileNames, file.file)
        .then((result) => {
          //下面是如果对返回结果再进行处理，根据项目需要
          this.form.img.push({
            path: fileNames,
            media_type: 1,
            width: this.width,
            height: this.height,
          });
          self.$message({
            message: "上传成功",
            type: "success",
          });
        })
        .catch((err) => {
          self.$message.error("上传失败");
        });
    },
    handlePictureCardPreview(file) {
      this.form.dialogImageUrl.push(file.url);
    },
    handleAvatarSuccess(res, file) {
      this.form.dialogImageUrl.push(URL.createObjectURL(file.raw));
    },
    handleSelectionChange(val) {
      this.ckeck = [];
      val.forEach((item) => {
        this.ckeck.push(item.id);
      });
      console.log(this.ckeck);
    },
    //提交
    submit() {
      this.$refs.form.validate((bol) => {
        if (bol) {
          this.loading = true;
          dynamicAdd({
            content: this.form.content,
            resource: this.form.img,
            type: this.form.type,
            id: this.form.id,
          }).then((res) => {
            if (res.code == 0) {
              this.$message({
                type: "success",
                message: "提交成功！",
              });
              this.dialogTableVisible = false;
              this.getList();
              this.loading = false;
            }
          });
        }
      });
    },
    //获取数据
    getList() {
      dynamicList({
        type: this.index,
        page: this.page,
        pageSize: this.pageSize,
        content: this.input1,
      }).then((res) => {
        if (res.code == 0) {
          this.total = parseInt(res.data.count);
          this.tableData = res.data.list;
        }
      });
    },
    search() {
      this.page = 1;
      this.getList();
    },
    del(id) {
      this.$confirm("确认要删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          dynamicDel({ id: [id] }).then((res) => {
            if (res.code == 0) {
              this.$message({
                type: "success",
                message: "删除成功！",
              });
              this.getList();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    delAll() {
      if (this.ckeck.length == 0) {
        this.$message({
          type: "error",
          message: "选择不能为空！",
        });
        return;
      }
      this.$confirm("确认要删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          dynamicDel({ id: this.ckeck }).then((res) => {
            if (res.code == 0) {
              this.$message({
                type: "success",
                message: "删除成功！",
              });
              this.getList();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    send(id) {
      this.$confirm("确认要发送吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "success",
      })
        .then(() => {
          dynamicSend({ id: [id] }).then((res) => {
            if (res.code == 0) {
              this.$message({
                type: "success",
                message: "发送成功！",
              });
              this.getList();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消发送",
          });
        });
    },
    sendAll() {
      if (this.ckeck.length == 0) {
        this.$message({
          type: "error",
          message: "选择不能为空！",
        });
        return;
      }
      this.$confirm("确认要发送吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "success",
      })
        .then(() => {
          dynamicSend({ id: this.ckeck }).then((res) => {
            if (res.code == 0) {
              this.$message({
                type: "success",
                message: "发送成功！",
              });
              this.getList();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消发送",
          });
        });
    },
    close() {
      this.$refs.form.resetFields();
      this.form.img = [];
      this.form.video = "";
      this.loading = false;
    },
    closeB() {
      // this.$refs.form.resetFields();
      // this.form.img = [];
      // this.loading = false;
    },
    importBtn() {
      this.dialogTableVisibleB = true;
    },
    beforeUpload(file) {
      //       if (
      //   [
      //     "image/jpeg",
      //     "video/ogg",
      //     "video/flv",
      //     "video/avi",
      //     "video/wmv",
      //     "video/rmvb",
      //   ].indexOf(file.type) == -1
      // ) {
      //   this.$message.error("请上传正确的图片格式");
      //   return false;
      // }
      if (this.form.dialogImageUrl.length >= 9) {
        this.$message({
          type: "error",
          message: "超过最大上传限制！",
        });
        return false;
      } else {
        //处理高宽
        let that = this;
        let _URL = window.URL || window.webkitURL;
        let image = new Image();
        console.log(image);
        image.onload = function () {
          console.log(image.width);
          console.log(image.height);
          that.width = image.width + "";
          that.height = image.height + "";
          return true;
        };
        image.src = _URL.createObjectURL(file);
      }
    },
    beforeUploadA(file) {
      console.log(file);
    },
    async upLoadA(file) {
      const res = await ossToken({
        type: 0,
      });
      if (res.code == 0) {
        this.dataObj = {
          accessKeyId: res.data.accessKey,
          accessKeySecret: res.data.accessSecret,
          securityToken: res.data.token,
          region: "oss-cn-hangzhou",
          bucket: res.data.bucket,
        };
      }
      const self = this;
      // console.log(file);
      let new_zip = new JsZip();
      new_zip.loadAsync(file.file).then((zip) => {
        this.plArr.forEach((item) => {
          new_zip
            .file(item.image)
            .async("blob")
            .then(function (content) {
              // let img = URL.createObjectURL(content);
              // console.log(img);
              item.image = "/img/" + item.image;
              client(self.dataObj)
                .multipartUpload(item.image, content)
                .then((res) => {
                  if (res.res.statusCode == 200) {
                    self.uped++;
                    self.progress = (self.uped / self.plArr.length) * 100;
                    if (self.uped == self.plArr.length) {
                      self.active = 2;
                    }
                  }
                })
                .catch();
            });
        });
      });
    },
    importfxx(obj) {
      let _this = this;
      console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxx1");
      let inputDOM = this.$refs.inputer;
      // 通过DOM取文件数据
      this.file = event.currentTarget.files[0];
      var rABS = false; //是否将文件读取为二进制字符串
      var f = this.file;
      var reader = new FileReader();
      //if (!FileReader.prototype.readAsBinaryString) {
      FileReader.prototype.readAsBinaryString = function (f) {
        var binary = "";
        var rABS = false; //是否将文件读取为二进制字符串
        var pt = this;
        var wb; //读取完成的数据
        var outdata;
        var reader = new FileReader();
        reader.onload = function (e) {
          var bytes = new Uint8Array(reader.result);
          var length = bytes.byteLength;
          for (var i = 0; i < length; i++) {
            binary += String.fromCharCode(bytes[i]);
          }
          var XLSX = require("xlsx");
          if (rABS) {
            wb = XLSX.read(btoa(fixdata(binary)), {
              //手动转化
              type: "base64",
            });
          } else {
            wb = XLSX.read(binary, {
              type: "binary",
            });
          }
          outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]); //outdata就是你想要的东西
          _this.getExcel(outdata);
        };
        reader.readAsArrayBuffer(f);
      };
      if (rABS) {
        reader.readAsArrayBuffer(f);
      } else {
        reader.readAsBinaryString(f);
      }
    },
    getExcel(arr) {
      console.log(arr);
      let bol = true;
      let errorArr = [];
      arr.forEach((item, index) => {
        let point = item.image.lastIndexOf(".");
        let suffix = item.image.substr(point);
        if (suffix != ".jpg") {
          bol = false;
          errorArr.push(index + 1);
        }
      });
      if (bol) {
        this.plArr = JSON.parse(JSON.stringify(arr));
        this.active = 1;
        this.txt = "";
      } else {
        let line = errorArr.join(",");
        this.txt =
          "excel文件中有不是jpg格式的图片分别在第" +
          line +
          "行，请处理后后再重新上传！";
      }
    },
    submitA() {
      console.log(this.plArr);
    },
    //上传视频前

    beforeUploadVideo(file) {
      if (
        [
          "video/mp4",
          "video/ogg",
          "video/flv",
          "video/avi",
          "video/wmv",
          "video/rmvb",
        ].indexOf(file.type) == -1
      ) {
        this.$message.error("请上传正确的视频格式");
        return false;
      } else {
        return true;
      }
    },
    // 上传成功
    handleVideoSuccess(res, file) {
      //获取上传图片地址
      // this.videoFlag = false;
      // this.videoUploadPercent = 0;
      // if(res.status == 200){
      //     this.videoForm.videoUploadId = res.data.uploadId;
      //     this.videoForm.Video = res.data.uploadUrl;
      // }else{
      //     this.$message.error('视频上传失败，请重新上传！');
      // }
      this.form.video = URL.createObjectURL(file.raw);
    },
    // 上传视屏
    async upLoadA(file) {
      await ossToken({
        type: 1,
      }).then((res) => {
        if (res.code == 0) {
          this.dataObj = {
            accessKeyId: res.data.accessKey,
            accessKeySecret: res.data.accessSecret,
            securityToken: res.data.token,
            region: "oss-cn-hangzhou",
            bucket: res.data.bucket,
          };
        }
      });
      const self = this;
      let files = file.file,
        point = files.name.lastIndexOf("."),
        suffix = files.name.substr(point),
        fileName = files.name.substr(0, point),
        date = Date.parse(new Date()),
        // fileNames = "/img/" + file.file.name;
        fileNames =
          "/video/" +
          Math.round(new Date() / 1000) +
          "." +
          file.file.name.substring(file.file.name.lastIndexOf(".") + 1);
      console.log(fileNames);
      // console.log(file.file.name.substring(file.file.name.lastIndexOf(".")+1));
      //fileNames上传文件的名称
      //file.file上传文件的内容
      client(this.dataObj)
        .multipartUpload(fileNames, file.file)
        .then((result) => {
          //下面是如果对返回结果再进行处理，根据项目需要
          this.form.img.push({
            path: fileNames,
            media_type: 2,
            width: "0",
            height: "0",
          });
          self.$message({
            message: "上传成功",
            type: "success",
          });
        })
        .catch((err) => {
          self.$message.error("上传失败");
        });
    },
  },
  created() {
    this.getList();
  },
  computed: {
    srcList: () => {
      return (arr) => {
        let list = [];
        arr.forEach((item) => {
          if (item.media_type == 1) {
            list.push(item.path);
          }
        });
        return list;
      };
    },
  },
  // watch: {
  //   uped: (value) => {
  //     console.log(value);
  //     console.log(this.plArr);
  //   },
  // },
};
</script>

<style lang="less" scoped>
.dynamicSend {
  padding: 20px;
  .inputA {
    width: 300px;
  }
  .btnA {
    float: right;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 80px;
    height: 80px;
    line-height: 80px;
    text-align: center;
    vertical-align: top;
    margin: 10px;
    border: 1px dashed #8c939d;
    border-radius: 5px;
  }
  .el-icon-delete {
    vertical-align: top;
    line-height: 80px;
    margin-top: 10px;
  }
  .avatar {
    width: 80px;
    height: 80px;
    margin: 10px;
    display: inline-block;
  }
  .submit {
    text-align: center;
  }
  /deep/ .el-table .cell {
    overflow: visible !important;
  }
  .up {
    text-align: center;
  }
  .video {
    width: 200px;
    height: 150px;
  }
}
</style>